import tbUtility as tb
import bizCsFields as cfm
import pandas as pd
import transFbTask as tft
from tabulate import tabulate

taskStatusMap = {
    "60418b08c679e20044c09c0c": "其他功能解决",
    "64af9ca33bb6c5ae1239f98e": "待开发评估",
    "654da2f56c338454318df4de": "待发布SIT(组内环境已测)",
    "5e0dabc57d161c00217800b8": "开发中",
    "6604cf0816117c37565adb54": "待开发",
    "5e0db98a8fc7b60022d301c6": "待组内评审",
    "6535cfab96d44880e05a51b1": "待测试",
    "6535cfab96d44880e05a51b4": "测试中",
    "5f40cf2267d6500044ec1a29": "待分析",
    "6535cfab96d44880e05a51b7": "已发布SIT(合入release部署)",
    "5e0dabc57d161c00217800b9": "已发布生产",
    "614407e924ae43003fd05019": "已完成（不发版）",
    "603ddbf166272e0044b3d934": "已发布UAT",
    "5e0dabc57d161c00217800b7": "待产品内审",
    "5e0db97739a39700233b0199": "待审阅",
    "6340edfabb167700408b7339": "经评估无法实现",
    "65e80e978ec65144610baca1": "待架构组评审",
}


def main(sprintList):
    task_list = []
    task_res = tb.fetchSprintData(sprintList)
    customFieldsMap = cfm.getCustomFieldsMap()
    for task in task_res:
        if task["id"] is None:
            continue
        if taskStatusMap.get(task["tfsId"], "unknow") not in [
            "已发布生产",
            "已完成（不发版）",
        ]:
            continue
        customFields = task["customfields"]
        task_extra = {}
        for cf in customFields:
            if cf["cfId"] == customFieldsMap["acceptance_department"]:
                task_extra["acceptance_department"] = cf["value"][0]["title"]
            elif cf["cfId"] == customFieldsMap["requirement_source"]:
                task_extra["requirement_source"] = cf["value"][0]["title"]
        # 过滤出客户成功部的需求
        if task_extra.get("acceptance_department", None) not in ["客户成功部"]:
            continue
        if task_extra.get("requirement_source", None) not in [
            "客成-重点客户满意度卡点",
            "客成-卡续约/增购/扩购",
        ]:
            continue
        data = {}
        task_id = task["id"]
        data["task_id"] = task_id
        data["task_no"] = "DB-" + str(task["uniqueId"])
        data["task_links"] = []
        task_link_res = tb.fetchTaskLink(task_id)
        if task_link_res:
            data["task_links"] = task_link_res
        task_list.append(data)
    for task in task_list:
        task_related_list = []
        for link in task["task_links"]:
            if link is None or link["linked"] is None or "id" not in link["linked"]:
                continue
            task_detail = tb.getTaskDetail(link["linked"]["id"])
            if task_detail:
                task_no = ""
                if task_detail["projectId"] == "5e0da3df445ae00022c75e71":
                    task_no = "DB-" + str(task_detail["uniqueId"])
                elif task_detail["projectId"] == "5e18291b91d57a001a5797d4":
                    task_no = "FB-" + str(task_detail["uniqueId"])
                else:
                    task_no = "OTS-" + str(task_detail["uniqueId"])
                task_related_list.append(task_no)
        task["task_related_list"] = task_related_list
    tasks = pd.DataFrame(task_list)
    print(
        tasks[tasks["task_related_list"].apply(len) == 0][
            ["task_id", "task_no", "task_related_list"]
        ]
    )


def getParentTask():
    sprint_data = tb.fetchSprintData(
        [
            "202508-2",
            "202509-1",
            "202509-2",
            "202510-1",
            "202510-2",
            "202511-1",
            "202511-2",
        ]
    )
    fatherTasksId = []
    for d in sprint_data:
        if "parentTaskId" in d and d["parentTaskId"] not in fatherTasksId:
            fatherTasksId.append(d["parentTaskId"])
    return fatherTasksId


def dataA(sprint_name, a_type="all"):
    # a_type: all,summary, nowork,isfather

    # 获取没有正向关联的内部需求列表
    father_tasks = getParentTask()
    data = []
    res = tb.fetchSprintData([sprint_name])
    for task in res:
        data.append(tft.transFbTask(task, father_tasks))
    d = pd.DataFrame(data)
    d = d[~d["biz_team"].isin(["私有云组", "报表组"])]
    # 统计需求分类工作量
    if a_type in ["all", "summary"]:
        a_one = d[d["is_father"] == False]
        a_one = (
            a_one.groupby(["task_type"])["estimate_workload"]
            .sum()
            .to_frame(name="workload")
            .reset_index()
        )
        print("**********需求分类工作量统计**********")
        print(tabulate(a_one, headers="keys", tablefmt="grid"))
    # 筛选没有评估人天需求
    if a_type in ["all", "nowork"]:
        a_two = d[d["is_father"] == False]
        a_two = a_two[
            (a_two["task_type"].isin(["客成需求", "交付需求"]))
            & (a_two["estimate_workload"] == 0)
        ]
        print("**********没有评估人天需求**********")
        print(tabulate(a_two, headers="keys", tablefmt="grid"))
    # 筛选isFather的数据
    if a_type in ["all", "isfather"]:
        a_three = d[d["is_father"] == True]
        print("**********父需求列表**********")
        print(tabulate(a_three, headers="keys", tablefmt="grid"))
    # 统计外部需求工作量
    if a_type in ["all", "teamSummary"]:
        a_four = d[d["is_father"] == False]
        a_four = (
            a_four[a_four["task_type"].isin(["客成需求", "交付需求","产品规划","技术规划"])]
            .groupby(["biz_team", "task_type"])["estimate_workload"]
            .sum()
            .to_frame(name="workload")
            .reset_index()
        )
        print("**********外部需求工作量统计**********")
        print(tabulate(a_four, headers="keys", tablefmt="grid"))
    # 未分类需求
    a_five = d[d["is_father"] == False]
    a_five = a_five[(a_five["task_type"] == "未定义")]
    print("**********未分类需求**********")
    print(tabulate(a_five, headers="keys", tablefmt="grid"))
    # 职能统计
    a_six = d[d["is_father"] == False]
    a_six = (
        a_six[~a_six["backend"].isin(["无需后端"])]
        .groupby(["biz_team", "backend"])["estimate_workload"]
        .sum()
        .to_frame(name="workload")
        .reset_index()
    )
    print("**********职能统计**********")
    print(tabulate(a_six, headers="keys", tablefmt="grid"))
    # 客户统计
    a_six = d[d["is_father"] == False]
    a_six = (
        a_six.groupby(["task_type", "main_customer"])["estimate_workload"]
        .agg(["sum", "count"])
        .reset_index()
    )
    print("**********客户统计**********")
    print(tabulate(a_six, headers="keys", tablefmt="grid"))


print("请选择迭代名：")
print("1. 202509-1")
print("2. 202509-2")
print("3. 202510-1")
print("4. 202510-2")
re_sprint = input("")
if re_sprint == "1":
    re_sprint = "202509-1"
elif re_sprint == "2":
    re_sprint = "202509-2"
elif re_sprint == "3":
    re_sprint = "202510-1"
elif re_sprint == "4":
    re_sprint = "202510-2"
else:
    print("请输入正确的迭代名")
    exit()
print("请输入分析类型：")
print("1. 全部")
print("2. 工作量发分类总计")
print("3. 没有评估人天需求")
print("4. 父需求列表")
print("5. 团队需求分类总计")
re_type = input("")
if re_type == "1":
    re_type = "all"
elif re_type == "2":
    re_type = "summary"
elif re_type == "3":
    re_type = "nowork"
elif re_type == "4":
    re_type = "isfather"
elif re_type == "5":
    re_type = "teamSummary"

else:
    re_type = "all"


dataA(re_sprint, re_type)
